package com.yonyou.pmclouds.basecom.filter;

import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.pmclouds.basecom.multilanguage.Language;
import com.yonyou.pmclouds.basecom.runtime.RpcUtils;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.yht.web.cas.util.CasClientUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class YHTWebContextInitFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //  判定移动端
        if (((HttpServletRequest) request).getServletPath().startsWith("/mobile")||((HttpServletRequest) request).getServletPath().startsWith("/outter")) {
            chain.doFilter(request, response);
            return;
        }
        String userId = CasClientUtils.getLoginedUserId();
        if (StringUtils.isEmpty(userId)) {
            userId = InvocationInfoProxy.getUserid();
        }
        RuntimeEnvironment.setLoginUserId(userId);
        String tenantId = this.getCookieValue((HttpServletRequest) request, (HttpServletResponse) response, "tenantid");
        if (StringUtils.isEmpty(tenantId)) {
            tenantId = InvocationInfoProxy.getTenantid();
        }
        RuntimeEnvironment.setTenantId(tenantId);
        InvocationInfoProxy.getTenantid();
        // 设置语言，目前按照中文处理
        RuntimeEnvironment.setLanguage(Language.SIMPLIFIEDCHINESE);
        //获取系统编码
        RuntimeEnvironment.setSysId(this.getCookieValue((HttpServletRequest) request, (HttpServletResponse) response, "sysid"));
        // 将数据塞入rpc的上下文中
        RpcUtils.setRpcContextFromRuntimeEnv();
        chain.doFilter(request, response);

    }

    public String getCookieValue(HttpServletRequest request, HttpServletResponse response, String key) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals(key)) {
                    value = c.getValue();
                    break;
                }
            }
        }
        return value;
    }

    @Override
    public void destroy() {

    }
}
